package com.icim.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;
import javax.naming.NameParser;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import com.icim.entity.Ret_wo;

@Repository
public class RetWoDao {
    @Resource
    private JdbcTemplate icimJdbcTemplate;

    private Ret_wo setEntity(ResultSet rs) throws SQLException {
        Ret_wo retWo = new Ret_wo();
        retWo.setWo_id(rs.getString("WO_ID"));
        retWo.setSo_id(rs.getString("SO_ID"));
        retWo.setCus_id(rs.getString("CUS_ID_FK"));
        retWo.setWo_typ(rs.getString("WO_TYP"));
        retWo.setFrom_thickness(rs.getDouble("FROM_THICKNESS"));
        retWo.setTo_thickness(rs.getDouble("TO_THICKNESS"));
        return retWo;
    }

    public List<Ret_wo> findWoListByCusId(String cusId) {
        String sql = "SELECT * FROM RET_WO WHERE WO_TYP='W' AND CUS_ID_FK = ?";
        return icimJdbcTemplate.query(sql, new Object[] { cusId }, new RowMapper<Ret_wo>() {

            @Override
            public Ret_wo mapRow(ResultSet rs, int rowNum) throws SQLException {
                return setEntity(rs);
            }

        });
    }

    public List<Ret_wo> getWo(String woId) {
        String sql = "SELECT * FROM RET_WO WHERE WO_ID = ?";
        return icimJdbcTemplate.query(sql.toString(), new Object[] { woId }, new RowMapper<Ret_wo>() {

            @Override
            public Ret_wo mapRow(ResultSet rs, int rowNum) throws SQLException {
                return setEntity(rs);
            }
        });
    }

    public List<Ret_wo> findWoListByWoIds(Collection<String> woCol, String woType) {

        // NamedParameterJdbcTemplate namedParameterJdbcTemplate = new
        // NamedParameterJdbcTemplate(icimJdbcTemplate);

        StringBuffer sql = new StringBuffer("SELECT * FROM RET_WO WHERE WO_TYP = ? and WO_ID IN ('', ");
        for (String str : woCol) {
            sql.append(", '").append(str).append("'");
        }

        return icimJdbcTemplate.query(sql.toString(), new Object[] { woType }, new RowMapper<Ret_wo>() {

            @Override
            public Ret_wo mapRow(ResultSet rs, int rowNum) throws SQLException {
                return setEntity(rs);
            }
        });

    }
}
